package com.zzl.gulimall.product.excepiton;

import com.alibaba.fastjson.JSON;
import com.zzl.common.exception.BizCodeEnume;
import com.zzl.common.exception.GuliMallException;
import com.zzl.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.MalformedParameterizedTypeException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Title: GuliMallExceptionAdvice.class<br>
 * Description: <br>
 * Copyright (c)  2021    <br>
 * Create DateTime: 2021/10/13 17:41 <br>
 *
 * @author zhuangzhuangliang
 */
@RestControllerAdvice(basePackages = "com.zzl.gulimall.product.controller")
@Slf4j
public class GuliMallExceptionControllerAdvice {

    /**
     * 处理数据校验异常
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R HandlerValidException(MethodArgumentNotValidException e){
        log.error("valid error");
        BindingResult bindingResult = e.getBindingResult();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        Map<String,String> map = new HashMap<>();
        fieldErrors.forEach(fieldError -> {
            map.put(fieldError.getField(),fieldError.getDefaultMessage());
        });
        return R.error(BizCodeEnume.VAILD_EXCEPTION.getCode(),BizCodeEnume.VAILD_EXCEPTION.getMsg()).put("data",map);
    }


    /**
     * 处理全局异常
     * @param e
     * @return
     */
    @ExceptionHandler(GuliMallException.class)
    public R handlerException(HttpServletRequest request, GuliMallException e){
        log.error("异常产生的路径：{},参数 {}",request.getRequestURI(), JSON.toJSONString(request.getParameterMap()));
        return R.error(BizCodeEnume.BUSINESS_EXCEPTION.getCode(), BizCodeEnume.BUSINESS_EXCEPTION.getMsg());
    }

    /**
     * 处理全局异常
     * @param e
     * @return
     */
    @ExceptionHandler(Throwable.class)
    public R handlerException(HttpServletRequest request, Throwable e){
        log.error("异常产生的路径：{},参数 {}",request.getRequestURI(), JSON.toJSONString(request.getParameterMap()));
        e.printStackTrace();
        return R.error(BizCodeEnume.UNKNOW_EXCEPTION.getCode(), BizCodeEnume.UNKNOW_EXCEPTION.getMsg());
    }
}
